/**
 * @Author: 陈瑞鹏
 * @Date:   2022-11-01 17:55:42
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2023-11-30 15:41:32
 */
import abiao_utils from "abiao_utils";
import express from "express";
import { Code } from "../enum/code.enum";
import JWT from "../utils/jwt";
import Result from "../utils/result";
import room from "../utils/socket/room";
import utils from "../utils/utils";
import Draw from "./draw.model";
import MUser from "./mUser.model";
import Room from "./room.model";

const gameRoute = express.Router();

/**
* @api {post} /login/enterGame 进入游戏
* @apiGroup 登录
* @apiDescription 创建角色并初始化角色数据  (在进入服务器时请求)
* @apiParam {String} openId 群黑唯一ID
* @apiParam {String} avatar 头像 (不参与加密)
* @apiParam {String} nickName 昵称 (不参与加密)
* @apiParam {Number} serverId 区服ID
* @apiParam {String} gameUrl 游戏地址 (不参与加密)
* @apiParam {String} chanel 渠道
* @apiParam {String} [ecid] 设备码 (不参与加密)  暂时可选
* @apiParam {String} time 时间戳
* @apiParam {String} sign 签名  md5(openId+serverId+time+key)
* @apiName enterGame
* @apiVersion 1.0.0
*/
gameRoute.post("/enterGame", async (req, res) => {
  let { openId, avatar, nickName, serverId, gameUrl, ecid, time, sign, evaluate } = req.body;

  let ip: string = utils.getClientIp(req);

  let endRole: any = await MUser.findOne({}).sort({ roleId: -1 });

  let UserRes: any = await MUser.findOne({ openId });

  let roleId: number;

  if (!UserRes) {
    roleId = !endRole ? 1 : Number(endRole.roleId) + 1;
    let info = {
      openId,
      roleId,
      avatar,
      nickName,
      regIp: ip,
      loginIp: ip,
      createTime: abiao_utils.date()
    }
    await MUser.create(info);
  } else {
    roleId = UserRes.roleId;
    if (!UserRes.status) {
      throw new Result(Code.Fail, '角色被封禁!');
    }
  }

  let token = JWT.generate({ roleId });
  await MUser.updateOne({ roleId }, {
    loginIp: ip, token, updateTime: abiao_utils.date(), avatar: avatar, nickName: nickName
  });

  let userRes = await MUser.findOne({ roleId });

  return res.json({ code: Code.Succ, message: "进入游戏", data: { userRes, token } });
})

/**
 * 创建房间
 */
gameRoute.post("/createRoom", async (req, res) => {
  let { roleId, gameId } = req.body;
  let endRoom: any = await Room.findOne({}).sort({ roomId: -1 });
  let roomId = !endRoom ? 1 : Number(endRoom.roomId) + 1;
  let userRes = await MUser.findOne({ roleId });
  let info = {
    roomId,
    roleId,
    gameId,
    roomData: [{
      roleId, isReady: true, money: 0, nickName: userRes['nickName'], iconUrl: userRes['avatar']
    }],
    createTime: abiao_utils.date()
  }
  await Room.create(info);

  let roomRes = await Room.findOne({ roomId });

  return res.json({ code: Code.Succ, message: "创建房间成功!", data: { roomRes } });
})

/**
 * 获取房间信息
 */
gameRoute.post("/getRoomRes", async (req, res) => {

  let { roleId, roomId, gameId } = req.body;
  let roomRes = null;
  if (roomId) {
    roomRes = await Room.findOne({ roomId, isDisMiss: false });
  } else {
    if (roleId) {
      roomRes = await Room.findOne({ roleId, isDisMiss: false });
    }
  }

  if (roomRes) {
    if (roomRes.gameId == gameId) {
      return res.json({ code: Code.Succ, message: "获取房间数据!", data: { roomRes } });
    } else {
      return res.json({ code: Code.Fail, message: "该游戏不存在该房间!", data: { url: "http://m.heitu.com/game/login.html?gid=" + roomRes.gameId } });
    }
  }
  return res.json({ code: Code.Succ, message: "获取房间数据!", data: { roomRes } });
})

/**
 * 保存抽奖配置数据
 */
gameRoute.post("/saveDrawData2", async (req, res) => {

  const { roomId, roleId, drawData, excludeArr } = req.body;

  let drawRes = await Draw.findOne({ roomId });

  let dData = JSON.parse(drawData);
  let eData = JSON.parse(excludeArr);

  if (!drawRes) {
    let info = {
      roomId,
      roleId,
      drawData: dData,
      excludeArr: eData,
      updateTime: abiao_utils.date(),
      createTime: abiao_utils.date(),
    }
    await Draw.create(info);
  } else {
    await Draw.updateOne({ roomId }, { excludeArr: eData, drawData: dData, updatTime: abiao_utils.date() });
  }

  let roomStr = "room_" + roomId;
  drawRes = await Draw.findOne({ roomId });
  room.send_room_msg("saveDrawData", { message: `修改抽奖配置数据`, drawRes }, roomStr);

  return res.json({ code: Code.Succ, message: "保存成功!", drawRes });
})
export default gameRoute;